package cn.bootx.table.modify.postgresql.entity;

import cn.bootx.table.modify.postgresql.constants.PgSqlIndexType;
import cn.bootx.table.modify.postgresql.util.PgSqlInfoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.List;

/**
 * 索引信息
 * @see cn.bootx.table.modify.postgresql.annotation.DbPgSqlIndex
 * @author xxm
 * @since 2023/4/10
 */
@Getter
@Setter
@Accessors(chain = true)
public class PgSqlEntityIndex {

    /** 类型 */
    private PgSqlIndexType type;

    /** 名称 */
    private String name;

    /** 唯一索引 */
    private boolean unique;

    /** 并发 */
    private boolean concurrently;

    /** 字段名称 */
    private List<String> columns;

    /** 注释 */
    private String comment;

    /**
     * 转换成索引创建语句
     * CREATE INDEX CONCURRENTLY "indexName" ON "tablename" USING brin (
     *   "a1", "a2"
     * );
     *
     */
    public String toIndexCreate(String tableName){
        String createIndex = StrUtil.format("CREATE {} INDEX {} \"{}\" ON \"{}\""
                , unique ? "UNIQUE " : ""
                , concurrently ? "CONCURRENTLY " : ""
                , getName()
                , tableName);
        StringBuilder sb = new StringBuilder(createIndex);
        sb.append(" USING ")
                .append(getType().name().toLowerCase())
                .append(PgSqlInfoUtil.buildBracketParams(getColumns()))
                .append(";");
        return sb.toString();
    }

    /**
     *  转换成索引备注语句
     *  COMMENT ON INDEX "index" IS 'Comment';
     */
    public String toIndexComment(){
        return StrUtil.format("COMMENT ON INDEX \"{}\" IS '{}';", getName(), getComment());
    }
}
